<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="病房号" prop="wardId">
        <el-select
            v-model="queryParams.wardId"
            placeholder="请选择病房号"
            clearable
            @change="handleQuery"
            style="width: 200px;"
        >
          <el-option
              v-for="ward in wardList"
              :key="ward.wardId"
              :label="ward.wardNumber"
              :value="ward.wardId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['nurse:bed:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['nurse:bed:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['nurse:bed:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['nurse:bed:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 病房列表 -->
    <el-collapse v-model="activeWardIds" accordion>
      <el-collapse-item
          v-for="ward in groupedWardList"
          :key="ward.wardId"
          :name="ward.wardId"
      >
        <template #title>
          <span class="ward-title">{{ ward.wardNumber }} ({{ ward.wardAdress }})</span>
        </template>
        <!-- 病床列表 -->
        <el-table
            :data="ward.beds"
            style="width: 100%"
            @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="床位号" align="center" prop="bedNumber" />
          <el-table-column label="床位状态" align="center">
            <template #default="scope">
              {{ scope.row.bedStatus === 0 ? '可用' : scope.row.bedStatus === 1 ? '占用' : '未知' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['nurse:bed:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['nurse:bed:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改病床管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="bedRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="病房号" prop="wardId">
          <el-select
              v-model="form.wardId"
              placeholder="请选择病房号"
              filterable
              @change="handleWardChange"
          >
            <el-option
                v-for="ward in wardList"
                :key="ward.wardId"
                :label="`${ward.wardNumber} (${ward.wardAdress})`"
                :value="ward.wardId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="床位号" prop="bedNumber">
          <el-input
              v-model="form.bedNumber"
              placeholder="请输入床位号"
          />
        </el-form-item>

        <el-form-item label="床位状态" prop="bedStatus">
          <el-select v-model="form.bedStatus" placeholder="请选择状态">
            <el-option label="可用" value="0"></el-option>
            <el-option label="占用" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Bed">
import { listBed, getBed, delBed, addBed, updateBed, getWard } from "@/api/nurse/bed";
import { computed, ref, reactive, getCurrentInstance, toRefs } from "vue";

const { proxy } = getCurrentInstance();
const wardList = ref([]); // 存储病房列表
const bedList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const activeWardIds = ref([]); // 当前展开的病房 ID

// 获取病房列表
function getWardList() {
  getWard().then((response) => {
    wardList.value = response || [];
  });
}

// 计算属性：将病床按病房分组
const groupedWardList = computed(() => {
  const grouped = {};
  bedList.value.forEach(bed => {
    const wardId = bed.wardId || 'unknown';
    if (!grouped[wardId]) {
      grouped[wardId] = {
        wardId: wardId,
        wardNumber: bed.mwardInfo?.wardNumber || '无',
        wardAdress: bed.mwardInfo?.wardAdress || '无',
        beds: []
      };
    }
    grouped[wardId].beds.push(bed);
  });
  return Object.values(grouped);
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    wardId: null,
  },
  rules: {
    wardId: [
      { required: true, message: "病房号不能为空", trigger: "blur" }
    ],
    bedNumber: [
      { required: true, message: "床位号不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询病床管理列表 */
function getList() {
  loading.value = true;
  listBed(queryParams.value).then(response => {
    bedList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    bedId: null,
    bedNumber: null,
    bedStatus: null,
    wardId: null,
  };
  proxy.resetForm("bedRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.bedId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加病床管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _bedId = row.bedId || ids.value;
  getBed(_bedId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改病床管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bedRef"].validate((valid) => {
    if (valid) {
      const submitData = {
        ...form.value,
        bedStatus: Number(form.value.bedStatus)
      };

      if (form.value.bedId != null) {
        updateBed(submitData).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBed(submitData).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _bedIds = row.bedId || ids.value;
  proxy.$modal.confirm('是否确认删除病床管理编号为"' + _bedIds + '"的数据项？').then(function() {
    return delBed(_bedIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('nurse/bed/export', {
    ...queryParams.value
  }, `bed_${new Date().getTime()}.xlsx`)
}

getList();
getWardList();
</script>

<style scoped>
.ward-title {
  font-size: 16px;
  font-weight: bold;
}
</style>